
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
const db = cloud.database()
const _ = db.command
export default async function (ctx: FunctionContext) {
  let body = ctx.body
  /**
   * {
   *     "id": "",
   *     "couponType": "CASH",
   *     "couponName": "三生鼎",
   *     "amount": "0",
   *     "conditionAmount": "0",
   *     "startTime": "2023-11-26",
   *     "endTime": "2023-11-30",
   *     "rangeType": "ALL",
   *     "rangeDesc": "",
   *     "publishCount": "121",
   *     "perLimit": "1",
   *     "useCount": "0",
   *     "receiveCount": "",
   *     "expireTime": "2023-11-30 00:00:00",
   *     "publishStatus": ""
   * }
   */
  if (nw.util.isNull(body._id)){
    return fail("参数不合法")
  }
  let couponInfo = await nw.db.findById({
    dbName:"couponInfo",
    id:body._id
  })
  if (nw.util.isNull(couponInfo)){
    return fail("优惠券不存在")
  }

  if (!nw.util.isNull(body.couponType)||!nw.util.isNull(body.couponName)){
    let whereJson = {deleted:0, couponType: undefined,couponName:undefined}
    if (!nw.util.isNull(body.couponType)&&!nw.util.isNull(body.couponName)){
      whereJson.couponType = _.eq(body.couponType)
      whereJson.couponName = _.eq(body.couponName)
    }else if (!nw.util.isNull(body.couponType)&&nw.util.isNull(body.couponName)){
      whereJson.couponType = _.eq(body.couponType)
      whereJson.couponName = _.eq(couponInfo.couponName)
    }else if (nw.util.isNull(body.couponType)&&!nw.util.isNull(body.couponName)){
      whereJson.couponType = _.eq(couponInfo.couponType)
      whereJson.couponName = _.eq(body.couponName)
    }
    //校验类型-名称是否重复
    let count = await nw.db.count({
      dbName:"couponInfo",
      whereJson:whereJson
    })
    if (count>0){
      return fail("优惠券重复")
    }
  }

  //构建保存结果
  let data = {
    couponType : body.couponType ||couponInfo.couponType,
    couponName : body.couponName ||couponInfo.couponName,
    amount : body.amount || couponInfo.amount,
    conditionAmount : body.conditionAmount || couponInfo.conditionAmount,
    startTime : body.startTime ||couponInfo.startTime,
    endTime : body.endTime||couponInfo.endTime,
    rangeType : body.rangeType||couponInfo.rangeType,
    rangeDesc : body.rangeDesc||couponInfo.rangeDesc,
    publishCount : body.publishCount||couponInfo.publishCount,
    perLimit : body.perLimit ||couponInfo.perLimit,
    useCount : body.useCount ||couponInfo.useCount,
    receiveCount : body.receiveCount ||couponInfo.receiveCount,
    expireTime : body.expireTime||couponInfo.expireTime,
    publishStatus : body.publishStatus ||couponInfo.publishStatus,
    createTime:couponInfo.createTime,
    updateTime:new Date(),
    deleted:0
  }

  let count = await nw.db.update({
    dbName:"couponInfo",
    whereJson:{_id:couponInfo._id},
    dataJson:data
  })
  if (count===0){
    return fail("编辑失败")
  }

  return ok("编辑成功")

}
